import { createRouter, createWebHashHistory } from "vue-router";
import { useUserStore } from "../store/userStore";
const router = createRouter({
  history: createWebHashHistory(),
  routes: [
    {
      path: "/",
      component: () => import("../views/main.vue"),
      redirect: "/home",
      children: [
        {
          path: "home",
          component: () => import("../views/home.vue"),
        },
        {
          path: "cart",
          component: () => import("../views/cart.vue"),
        },
        {
          path: "mine",
          component: () => import("../views/mine.vue"),
        },
      ],
    },
    {
      path: "/test",
      component: () => import("../views/test/index.vue"),
    },
    {
      path: "/pinia",
      component: () => import("../views/pinia/index.vue"),
    },
    {
      path: "/detail",
      component: () => import("../views/detail.vue"),
    },
    {
      path: "/login",
      component: () => import("../views/login.vue"),
    },
    {
      path: "/reg",
      component: () => import("../views/reg.vue"),
    },
    {
      path: "/order",
      component: () => import("../views/order.vue"),
    },
    {
      path: "/address/list",
      component: () => import("../views/address/list.vue"),
    },
    {
      path: "/address/add",
      component: () => import("../views/address/add.vue"),
    },
  ],
});

let controlList = ["/cart", "/mine"];
router.beforeEach((to, from, next) => {
  const user = useUserStore();
  if (controlList.includes(to.path)) {
    if (user.userInfo) {
      next();
    } else {
      next({
        path: "/login",
        query: {
          target: to.path,
        },
      });
    }
  } else {
    next();
  }
});

export default router;
